const gulp = require('gulp')
const {dest} = gulp
const clean = require('gulp-clean')
const imageMinNokey = require('gulp-tinypng-nokey')
const imageMinWithKey = require('gulp-tinypng-compress')

// 清除目标文件夹
gulp.task('delete', () => {
  return gulp.src('images', {allowEmpty: true})
  .pipe(dest('images'))
})
// 复制所有图片到目标文件夹以防丢失
gulp.task('copy-image', (done) => {
  gulp.src('images/**/*')
  .pipe(dest('image-target'))
  done()
})
// 图片压缩不需要key
gulp.task('image-min-nokey', (done) => {
  gulp.src('images/**/*.{png,jpg}')
  .pipe(imageMinNokey({
    log: true
  }))
  .pipe(dest('image-target'))
  done()
})

// 图片压缩需要key
gulp.task('image-min', (done) => {
  gulp.src('images/**/*.{png,jpg}')
  .pipe(imageMinWithKey({
    log: true,
    key: 'xxxxxxxxxxxxxx'   // 到以下网站(https://tinypng.com/developers)获取key，每个账号每月500张图片免费次数
  }))
  .pipe(dest('image-target'))
  done()
})

// 没有key执行该任务
gulp.task('build', gulp.series('delete', 'copy-image', gulp.parallel('image-min-nokey')), (done) => {
  done()
})

// 有key情况
gulp.task('build-key', gulp.series('delete', 'copy-image', gulp.parallel('image-min')), (done) => {
  done()
})
